#-*- coding: utf-8 -*-

import time, sys
import random
import sqlite3

import urllib2
import urllib

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from ui.Core import *


import browser_bogus
import online_keeper
from user_agent_lib import get_random_user_agent
from browser_bogus import Browser


try:
    _fromUtf8 = QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s


VERSION = "2.6.1"
       

"""==================================================================================="""

login_page = "http://bbs.pcbeta.com/member.php?mod=logging&action=login";
task_page = "http://i.pcbeta.com/home.php?mod=task";
task_doing_page = "http://i.pcbeta.com/home.php?mod=task&item=doing";
bangui_leaarn_pg1 = "http://bbs.pcbeta.com/viewthread-951045-7575-1.html";
post_bangui_learn_pg = "http://bbs.pcbeta.com/forum.php?mod=post&action=reply&extra=page%3D1&replysubmit=yes&infloat=yes&handlekey=fastpost&inajax=1";


if __name__ == "__main__":
    random.seed()
    user = browser_bogus.Browser('elsesky', 'iRubyzQJugzLoYjT_QASWDst}STkb6XbaXCmnXb}', get_random_user_agent())
    
    url = login_page
#First access,get COOKIE and store
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    content = result.read();
#     print content;
#get the value of loginhash
    vloginhash = content.split("loginhash=")[1].split("\"")[0]
#     print vloginhash;
#get the value of formhash
    vformhash = content.split("formhash\" value=\"")[1].split("\"")[0]
#     print vformhash;
#init content of post action
    logindata = {
                     "formhash":vformhash,
                     "referer":"http://bbs.pcbeta.com/./",
                     "questionid":"0",
                     "username":user.username,
                     "password":user.password,
                     "answer":"",
                     "cookietime":"2592000"
                }
    en_logindata = urllib.urlencode(logindata)
#init login post url
    url = url + "&loginsubmit=yes&inajax=1&loginhash=" + vloginhash;
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
#do login
    result = user.urlOpener.open(request)
#check login
    if result.read().find("欢迎您回来".decode("utf-8").encode("gbk")) < 0:
        print "登录失败"
    else:
        print "用户".decode('utf-8').encode('gbk') + user.username + "已成功登录".decode('utf-8').encode('gbk')

#get task page
    print "检查是否存在新任务".decode("utf-8").encode("gbk")  
    url = task_page;
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    task_content = result.read();
    tasks = task_content.split("http://static.pb.pbcdn.com/static/image/task/apply.gif");
#get all task url
    tasks.pop(len(tasks) - 1);
    tsklen = len(tasks);
#     i = 0
    for tsk in tasks:
#get task url ;be careful with & code
#         tasks[i] = tsk.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&");
#         print tasks[i]
#         request = urllib2.Request(tasks[i])
        request = urllib2.Request(tsk.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&"))
        request.add_header("User-Agent", user.user_agent)
#apply all tasks
        result = user.urlOpener.open(request)
#         print result.read();
#         i += 1
    if tsklen > 0:
        print "任务申请成功".decode("utf-8").encode("gbk");
    else:
        print "无新任务".decode("utf-8").encode("gbk");
#     print task_content;




#DO POST Thread
    url = bangui_leaarn_pg1;
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    bangui_leaarn_pg1_content = result.read();
    vtformhash = bangui_leaarn_pg1_content.split("formhash\" value=\"")[1].split("\"")[0]
#获取当前帖子提交的fid以及tid     
    fid_tid = "&fid=" + bangui_leaarn_pg1_content.split('post&action=reply&fid=') [1].split("'")[0];
#     print fid_tid;
#     print vtformhash;exit;
#     print bangui_leaarn_pg1_content;
#init content of thread post action
    threaddata = {
                     "formhash":vtformhash,
                     "message":"每日学习新版规".decode('utf-8').encode('gbk'),
                     "posttime":str(time.time()).split(".")[0],#提取当前时间
                     "subject":"",
                     "usesig":"1"
                }
    en_logindata = urllib.urlencode(threaddata)
#init thread post url
    url = post_bangui_learn_pg + fid_tid;
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
#do thread post     
    result = user.urlOpener.open(request)
#check post
    if result.read().find("回复发布成功".decode("utf-8").encode("gbk")) < 0:
        print "发帖失败".decode('utf-8').encode('gbk')
    else:
        print "发帖成功".decode('utf-8').encode('gbk')
    
    
    
    
    
    
    
#get task doing page
    print "检查是否存在已经完成的任务".decode("utf-8").encode("gbk")    
    url = task_doing_page;
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    task_doing_content = result.read();
    tasksdone = task_doing_content.split("http://static.pb.pbcdn.com/static/image/task/reward.gif");
#get all task url
    tasksdone.pop(len(tasksdone) - 1);
    tasksdonelen = len(tasksdone);
#     i = 0
    for tskd in tasksdone:
#get taskdone url ;be careful with & code
#         tasksdone[i] = tskd.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&");
#         print tasksdone[i]
#         continue;
#         request = urllib2.Request(tasks[i])
        request = urllib2.Request(tskd.split("\"><img src=")[-2].split("<a href=\"")[-1].replace("&amp;" , "&"))
        request.add_header("User-Agent", user.user_agent)
#apply all have been done tasks
        result = user.urlOpener.open(request)
#         print result.read();
#         i += 1
    if tasksdonelen > 0:
        print "已完成的任务刷新完毕".decode("utf-8").encode("gbk");
    else:
        print "无需要刷新的已完成任务".decode("utf-8").encode("gbk");
    
    
    
#     print result.read();

    #QMessageBox.information(window, _fromUtf8("asdfaf"), _fromUtf8(result.read()))
                 
                 
                 
                 
                 
                              
                 
                 
     #complete the task 75
def make_task_complete_url(tid):
    return "http://i.pcbeta.com/home.php?mod=task&do=draw&id=" + tid;             
                 
                 
                 
                 
                 
                 
                 
                 
                 
    
    
    
    